<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import type { Product } from '@/types/product'
import { productService } from '@/services/apiService'
import { useUserStore } from '@/stores/user'
import { ElCard, ElButton, ElTable, ElTableColumn, ElTag, ElMessage, ElMessageBox } from 'element-plus'
import LoadingSpinner from '@/components/LoadingSpinner.vue'
import { computed } from 'vue'

const router = useRouter()
const userStore = useUserStore()
const BASE_URL = 'http://localhost:8000';

//头像URL路径
const fullAvatarUrl = computed(() => {
  if (!userStore.userAvatar) return '';
  const avatarPath = userStore.userAvatar.startsWith('/') ? userStore.userAvatar.slice(1) : userStore.userAvatar;
  return `${BASE_URL}/${avatarPath}`;
});

// 发布的商品列表
const myProducts = ref<Product[]>([])
const loading = ref(false)

// 获取用户发布商品列表
const fetchMyProducts = async () => {
  loading.value = true
  try {
    // 调用后端API获取用户发布的商品列表
    const response = await productService.getUserProducts(userStore.userInfo.id)
    myProducts.value = response.results || []
  } catch (error) {
    console.error('获取商品列表失败:', error)
    ElMessage.error('获取商品列表失败')
  } finally {
    loading.value = false
  }
}

// 编辑商品
const editProduct = (id: number) => {
  router.push(`/update/${id}`)
}

// 结束出售
const endSelling = (id: number) => {
  ElMessageBox.confirm('确定要结束该商品的出售吗？', '确认操作', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      // 构造更新数据
      const formData = new FormData()
      formData.append('status', '2')
      
      // 调用API更新商品状态
      await productService.updateProduct(id, formData)
      
      // 更新本地数据
      const product = myProducts.value.find(p => p.gid === id)
      if (product) {
        product.status = 2
        //user.value.sellCount += 1
      }
      
      ElMessage.success('商品已标记为已售出')
    } catch (error) {
      console.error('更新商品状态失败:', error)
      ElMessage.error('操作失败，请稍后重试')
    }
  }).catch(() => {
    // 用户取消操作
  })
}

// 删除商品
const deleteProduct = (id: number) => {
  ElMessageBox.confirm('确定要删除该商品吗？此操作不可撤销', '确认删除', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      // 调用API删除商品
      await productService.deleteProduct(id)
      
      // 更新本地数据
      myProducts.value = myProducts.value.filter(p => p.gid !== id)
      
      ElMessage.success('商品已删除')
    } catch (error) {
      console.error('删除商品失败:', error)
      ElMessage.error('删除失败，请稍后重试')
    }
  }).catch(() => {
    // 用户取消操作
  })
}

// 发布新商品
const createProduct = () => {
  router.push('/create')
}

// 页面初始化
onMounted(() => {
  //fetchUserInfo()
  fetchMyProducts()
})
</script>

<template>
  <div class="user-profile-container">
    <el-row :gutter="20">
      <el-col :span="8">
        <el-card class="profile-card">
          <div class="profile-header">
            <img :src="fullAvatarUrl" alt="用户头像" class="avatar" />
            <div class="profile-info">
              <h2>{{ userStore.userName }}</h2>
            </div>
          </div>
          <el-button type="primary" @click="createProduct" style="width: 100%; margin-top: 20px;">
            发布新商品
          </el-button>
        </el-card>
      </el-col>
      
      <el-col :span="16">
        <el-card class="products-card">
          <template #header>
            <h2>我的发布</h2>
          </template>
          
          <!-- 加载状态 -->
          <div v-if="loading" class="loading-container">
            <LoadingSpinner />
          </div>
          
          <!-- 商品列表 -->
          <div v-else>
            <el-table :data="myProducts" style="width: 100%" v-if="myProducts.length > 0">

              <el-table-column prop="title" label="商品名称" >
                <template #default="scope">
                  {{ scope.row.title }}
                </template>
              </el-table-column>

              <el-table-column prop="price" label="价格" width="100">
                <template #default="scope">
                  ¥{{ scope.row.price }}
                </template>
              </el-table-column>

              <el-table-column prop="view_count" label="浏览量" width="100">
                <template #default="scope">
                  {{ scope.row.view_count }}
                </template>
              </el-table-column>

              <el-table-column prop="status" label="状态" width="100">
                <template #default="scope">
                  <el-tag :type="scope.row.status === 1 ? 'success' : 'info'">
                    {{ scope.row.status === 1 ? '出售中' : '已售出' }}
                  </el-tag>
                </template>
              </el-table-column>

              <!-- status=0时是售出状态，不允许编辑和结束出售 -->
              <el-table-column label="操作" width="200">
                <template #default="scope">

                  <el-button 
                    size="small" 
                    @click="editProduct(scope.row.gid)"
                    :disabled="scope.row.status !== 1"
                  >
                  编辑商品
                  </el-button>

                  <el-button 
                    size="small" 
                    type="success" 
                    @click="endSelling(scope.row.gid)"
                    :disabled="scope.row.status !== 1"
                  >
                  结束出售
                  </el-button>

                  <el-button 
                    size="small" 
                    type="danger" 
                    @click="deleteProduct(scope.row.gid)"
                  >
                  删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            
            <!-- 无数据状态 -->
            <div v-if="!loading && myProducts.length === 0" class="no-data">
              <p>暂无发布商品</p>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>